<?php

# langito project
# vars cache and management class

class vars {
	var $cachePath; #path to folder storing all files with trailing / at the end
	var $rootDir; #path to root vars directory
	var $cacheTime; #time vars are cached, try $obj->set_time(seconds) to override defaults
	
	function files() {
		$this->cachePath=null;
		$this->rootDir='vars/';
	}
	
	function set_path($path) {
		if(strpos($path, '..')!==false or substr($path, 0, 1)=='/')
			die('You are allowed setting path only in ./ directory.');
			
		$this->cachePath=$path;
	}
	
	function get_var($varName, $file) {
		if(!file_exists($this->rootDir.$this->cachePath.$file)) die('File: '.$this->rootDir.$this->cachePath.$file.' doesn\'t exists...');
		
		$value=file_get_contents($this->rootDir.$this->cachePath.$file);
		
		if(strlen($value)>0) {
			$value=substr($value, 15); //ommit added exit in var files
			$GLOBALS[$varName]=unserialize($value);
		} else { //no saved values return clean array
			$GLOBALS[$varName]=array();
		}
	}
	
	function write_var($varName, &$varValue, $file) {
		//check for errors
		if(!$this->check_perms($file)) die('Set proper CHMOD to: '.$this->rootDir.$this->cachePath.$file);
		if(strpos($file, '.php')===false) die('Add *.php extension to file you want to save (security).');
		if(!file_exists($this->rootDir.$this->cachePath.$file)) die('File: '.$this->rootDir.$this->cachePath.$file.' doesn\'t exists...');
		
		//get old vars
		$this->get_vars('all', $this->rootDir.$this->cachePath.$file);
		
		$GLOBALS['all'][$varName]=$varValue;
		file_put_content($this->rootDir.$this->cachePath.$file, '<?php exit;?>'."\n\r".seralize($GLOBALS['all']));
		unset($GLOBALS['all']);
	}
	
	function remove_var($varName, $file) {
	}
	
	function check_perms ($file) {
		if(!file_exists($this->rootDir.$this->cachePath.$file)) return false;
		
		$fp=@fopen($this->cachePath.$file, 'r+');
		@fclose($fp);
		
		if(!$fp)
			return false;
		else
			return true;
	}
}

?>
